// 页面分页拉取
// this.paging = new Paging (getComments, {page: 0, limit: 10}, this.comments)
// this.pagin.next({tid:  this.tid}, res =>{})

class Paging {
  // current = 0 当前页 &初始页
  // limit = 10 每页多少条
  // isEnd = false 是否结束分页
  // resKey = 'data' 返回的列表中的数据键值
  // baginPage = 0 初始页

  constructor (api, options, resKey) {
    this.api = api
    this.dataList = []
    const { limit, page } = options
    this.options = options
    this.page = page || 0
    this.limit = limit || 10
    this.resKey = resKey || 'data'
    this.isEnd = false
  }
  getIsEnd () {
    return this.isEnd
  }
  // 获取下页数据，并调用后台接口
  async next () {
    if (this.isEnd) return
    // this.api(this.options)
    try {
      let res
      res = await this.api({ ...this.options, page: this.page, limit: this.limit })
      // res = await this.api(this.options)
      if (res.code === 200) {
        // console.log(res.data);
        if (res[this.resKey].length < this.limit) {
          this.isEnd = true
        }
        if (this.dataList.length === 0) {
          this.dataList = res[this.resKey]
        } else {
          this.dataList = this.dataList.concat(res[this.resKey])
        }
      }
      this.page++
    } catch (error) {
      if (error) {
        console.log('paging', error)
      }
    }
    return this.dataList
  }
  clear () {
    this.page = 0
    this.dataList = []
    this.isEnd = false
  }
}
// 清除数据
export default Paging
